package com.lm.netty.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author 11630
 */
@Configuration
@Slf4j
public class DataSourceConfig {

    @Value("${spring.datasource.douban.url}")
    private String doubanUrl;
    @Value("${spring.datasource.movie.url}")
    private String movieUrl;
    @Value("${spring.datasource.douban.driverClass}")
    private String driverClass;
    @Value("${spring.datasource.douban.username}")
    private String username;
    @Value("${spring.datasource.douban.password}")
    private String password;

    @Primary
    @Bean(name = "doubanDataSource")
    @Qualifier("doubanDataSource")
    public DataSource doubanDataSource() {
        return DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .driverClassName(driverClass)
                .url(doubanUrl)
                .username(username)
                .password(password)
                .build();
    }

    @Bean(name = "movieDataSource")
    @Qualifier("movieDataSource")
    public DataSource movieDataSource() {
        return DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .driverClassName(driverClass)
                .url(movieUrl)
                .username(username)
                .password(password)
                .build();
    }

    @Bean(name = "doubanJdbcTemplate")
    public JdbcTemplate doubanJdbcTemplate(@Qualifier("doubanDataSource") DataSource doubanDataSource) {
        return new JdbcTemplate(doubanDataSource);
    }

    @Bean(name = "movieJdbcTemplate")
    public JdbcTemplate movieJdbcTemplate(@Qualifier("movieDataSource") DataSource movieDataSource) {
        return new JdbcTemplate(movieDataSource);
    }

    @Bean(name = "doubanTransactionManager")
    public DataSourceTransactionManager doubanTransactionManager(@Qualifier("doubanDataSource") DataSource doubanDataSource){
        return new DataSourceTransactionManager(doubanDataSource);
    }
    @Bean(name = "movieTransactionManager")
    public DataSourceTransactionManager movieTransactionManager(@Qualifier("movieDataSource") DataSource movieDataSource){
        return new DataSourceTransactionManager(movieDataSource);
    }
}
